import React, { Component } from 'react';
import style from './Cart.module.scss'
import { NavBar } from 'antd-mobile'
import img from '../../utils/img'
import { connect } from "react-redux";
class Cart extends Component {
    state = {
        cartData:[],
        checked: true,
        a: 1
    }
    componentDidMount() {
        let data = localStorage.getItem("cart")
        // let data = this.props.cartData
        let cartData = JSON.parse(data || "[]")
        this.setState({//异步写入值
            cartData,
        })
        //判断初始时全选按钮的选中情况
        let bool = cartData.some(v => {
            if (!v.checked) {//如果有一个为未选中
                return true
            }
        })
        if (bool) {
            this.setState({
                checked: false,
            })
        }
    this.totalPrice(cartData)

    }
    //goodsSelect
    goodsSelect(index) {
        // this.state.cartData[index].checked = !this.state.cartData[index].checked
        let selext = this.state.cartData
        selext[index].checked = !selext[index].checked
        this.cartData = selext
        this.setState({
            cartData:[...this.state.cartData],
        })
        // localStorage.setItem("cart", JSON.stringify(this.cartData))
        let bool = this.cartData.some(v => {
            return v.checked == false
        })
        let check = this.state
        if (bool) {     
            check.checked = false
            this.setState({
                ...this.state
            })
        } else {
            check.checked = false
            this.setState({
                ...this.state
            })
        }
        this.totalPrice(selext)
    }
    //lessenNum
    lessenNum(index) {
        // let num = --this.state.cartData[index].num
        let num = this.state.cartData
         num = --num[index].num
        if (num <= 0) {
            
            this.state.cartData.splice(index, 1)
        }
        this.setState({
            cartData:[...this.state.cartData],
        })
        // localStorage.setItem("cart", JSON.stringify(this.state.cartData))
        this.totalPrice(this.state.cartData)

    }
    //addNum
    addNum(index) {
        let num = this.state.cartData
         ++num[index].num
        this.setState({
            cartData:[...this.state.cartData],
        })
        this.setState( ()=>{//三种传入形式 []  {}   ()=>{}  需要一个对象的状态变量更新或一个函数返回一个对象的状态变量
            console.log(this.state)  //只要其this.state里的值更新了就算这里setState([])orsetState({})都会重新更新this.state里的值（react里的setState不仅比对地址也比对属性值）
        })
        // localStorage.setItem("cart", JSON.stringify(num))
       this.totalPrice(num)
    }
    //checkAll
    checkAll = (check) => {
        let checked = !this.state.checked
        let change = true
        if (!checked) change = false
        this.state.cartData.forEach(v => {
            v.checked = change;
        })
        this.setState({
            cartData:[...this.state.cartData],
            checked,
        })
        this.totalPrice(this.state.cartData)
    }
    //计算总价和数量
    totalPrice(data){
        let money=0
        let totalNum=0
        console.log(data)
        data.forEach(v=>{
            if(v.checked){  money += v.goods_price*v.num
                totalNum +=v.num}
          
        })
        this.setState({
            money,
            totalNum
        })
        if(data[0]){
            data[0].money=money
            data[0].totalNum=totalNum
        }
     
        localStorage.setItem("cart", JSON.stringify(data))
        console.log(JSON.parse(localStorage.getItem("cart")))
    }
    //toPay
    toPay=()=>{
        console.log(this.props)
        this.props.history.push("/pay")
    }
    render() {
        return (
            <div className={style.cartContent}>
                {!!this.state.cartData.length ?
                    <div className={style.cartContentShopping}>
                        <NavBar className={style.cartContentShoppingNav}

                        >优购商城</NavBar>
                        <div className={style.cartContentShoppingItem}>
                            {this.state.cartData.map((v, index) => {
                                return <div className={style.cartContentShoppingItemList} key={v.goods_id}>
                                    <div className={style.cartContentChecked}><i onClick={this.goodsSelect.bind(this, index)} className={!v.checked ? "iconfont icon-yuancircle46" : "iconfont icon-check1" + " " + style.color}></i></div>
                                    <img src={v.goods_small_logo} alt="" />
                                    <div className={style.itemListTitle}>
                                        <div className={style.itemListTitleTop}>{v.goods_name}</div>
                                        <div className={style.itemListPrice}>
                                            <span>￥{v.goods_price}</span>
                                            <div className={style.itemListPriceButton}>
                                                <i onClick={this.lessenNum.bind(this, index)} className="iconfont icon-jianhao"></i>
                                                <div className={style.itemListPriceNum}>{v.num}</div>
                                                <i onClick={this.addNum.bind(this, index)} className="iconfont icon-jiahao"></i>
                                            </div>
                                        </div>
                                    </div>

                                </div>
                            })}
                        </div>
                        <div className={style.bottom}>
                            <div className={style.bottomChecked}>
                                <i onClick={this.checkAll} className={this.state.checked ? "iconfont icon-check1" : "iconfont icon-yuancircle46"}></i>
                                <span>全选</span>
                                <div className={style.bottomPrice}>合计&nbsp;:&nbsp;￥{this.state.money}</div>
                            </div>
                            <div className={style.bottomToPay} onClick={this.toPay}>去结算({this.state.totalNum})</div>
                        </div>
                    </div>
                    : <div><img src={img.empty} alt="" className={style.cartContentImgEmpty}></img><a href="#/category">去逛逛</a> </div>
                }
            </div>
        );
    }
}



const mapState = (state) => {
    return {
      cartData: state.cartReducer.cartData,
    };
  };
  const mapDispatch = (dispatch) => {
    //
    return {
        type:'',
        value:{

        },
    };
  };
  
  export default connect(mapState, mapDispatch)(Cart);
